import { memo, useEffect, useRef, useState } from 'react';
import type { FC, PropsWithChildren } from 'react';
import { PageHeader } from 'antd';
import { resAddressList } from '@/services/address';
import { useRequest } from 'ahooks';
import AddressCard from '@/components/AddressCard';
import ProfileContainer from '@/components/ProfileContainer';

const AddressPage: FC<PropsWithChildren<{}>> = () => {
  const { data: addresses, run } = useRequest(resAddressList);
  const [addressId, setAddressId] = useState(0);
  const unmounted = useRef(false);
  useEffect(() => {
    if (addresses && !unmounted.current) {
      setAddressId(addresses?.find((value) => Boolean(value.is_default))?.id!);
    }
    return () => {
      unmounted.current = true;
    };
  }, [addresses]);
  return (
    <ProfileContainer title={'收货地址'}>
      <div className={'px-10 py-5'}>
        <div>
          {addresses ? (
            <AddressCard
              checkedValue={addressId!}
              onChange={(id) => {
                setAddressId(id);
              }}
              data={addresses}
              run={run}
            />
          ) : null}
        </div>
      </div>
    </ProfileContainer>
  );
};

export default memo(AddressPage);
